$(function() {
	/*
	number of fieldsets
	*/
	var fieldsetCount = $('#slidingFormFieldsetDiv').children().length;
	
	/*
	current position of fieldset / navigation link
	*/
	var current 	= 1;
    
	/*
	sum and save the widths of each one of the fieldsets
	set the final sum as the total width of the steps element
	*/
	var stepsWidth	= 0;
  var widths 		= new Array();
	$('#steps .step').each(function(i){
        var $step 		= $(this);
        widths[i]  		= stepsWidth;
        stepsWidth	 	+= $step.width();
    });
	$('#steps').width(stepsWidth);
	
	/*
	to avoid problems in IE, focus the first input of the form
	*/
	//$('#slidingFormFieldsetDiv').children(':first').find(':input:first').focus();	
	
	/*
	show the navigation bar
	*/
	$('#navigation').show();
	
  
  
  // JF
  handleServerValidationError();
  
  
  
	/*
	when clicking on a navigation link 
	the form slides to the corresponding fieldset
	*/
  $('#navigation a').bind('click',function(e){
		var $this	= $(this);
		var prev	= current;
		$this.closest('ul').find('li').removeClass('selected');
        $this.parent().addClass('selected');
		/*
		we store the position of the link
		in the current variable	
		*/
		current = $this.parent().index() + 1;
		/*
		animate / slide to the next or to the corresponding	fieldset. The order of the links in the 
    navigation is the order of the fieldsets.	Also, after sliding, we trigger the focus on the 
    first input element of the new fieldset. If we clicked on the last link (confirmation), 
    then we validate all the fieldsets, otherwise we validate the previous one
		before the form slided
		*/
     $('#steps').stop().animate({
          marginLeft: '-' + widths[current-1] + 'px'
      },500,function(){
        
        if(current == fieldsetCount) {
          //validateSteps();
        }
        else {
          //validateStep(prev);
        }
        $('#slidingFormFieldsetDiv').children(':nth-child('+ parseInt(current) +')').find(':input:first').focus();	
		});
        e.preventDefault();
  });
	
	/*
	clicking on the tab (on the last input of each fieldset), makes the form
	slide to the next step
	*/
	$('#slidingFormFieldsetDiv > fieldset').each(function(){
		var $fieldset = $(this);
		$fieldset.children(':last').find(':input').keydown(function(e){
			if (e.which == 9){
				$('#navigation li:nth-child(' + (parseInt(current)+1) + ') a').click();
				/* force the blur for validation */
				$(this).blur();
				e.preventDefault();
			}
		});
	});
	
	/*
	validates errors on all the fieldsets
	records if the Form has errors in $('#slidingFormFieldsetDiv').data()
	*/
	function validateSteps(){
		var FormErrors = false;
		for(var i = 1; i < fieldsetCount; ++i){
			var error = validateStep(i);
			if(error == -1)
				FormErrors = true;
		}
		$('#slidingFormFieldsetDiv').data('errors',FormErrors);	
	}
	
	/*
	validates one fieldset
	and returns -1 if errors found, or 1 if not
	*/
	function validateStep(step){
		if(step == fieldsetCount) return;  // no fields to check in the 'submit' fieldset?
		
		var error = 1;
		var hasError = false;
		$('#slidingFormFieldsetDiv').children(':nth-child('+ parseInt(step) +')').find(':input:not(button)').each(function(){
			var $this 		= $(this);
			var valueLength = jQuery.trim($this.val()).length;
			
			if(valueLength == ''){
				hasError = true;
				$this.css('background-color','#FFEDEF');
			}
			else
				$this.css('background-color','#FFFFFF');	
		});
    
		var $link = $('#navigation li:nth-child(' + parseInt(step) + ') a');
		$link.parent().find('.clientSideError,.checked').remove(); // remove any previously applied 'clientSideError' or 'checked' state
		
		var valclass = 'checked';
		if(hasError){
			error = -1;
			valclass = 'clientSideError';
		}
		$('<span class="'+valclass+'"></span>').insertAfter($link);
		
		return error;
	}
	
  /**
   *  Put a red x image in approp places if server placed an 'error' class
   */
  function handleServerValidationError() {

    $('.error').each(function(){
      
      var $this = $(this);
      // get the accoridan tab anchor element of the fielset with this error
      var $mainFieldset = $this.closest('.addFieldset');
      var $fieldsetErrorAnchor = $mainFieldset.prev('h3').children('a'); 
      //var $fieldsetErrorAnchor = $this.closest('.addFieldset').prev('h3').children('a'); 
      // add a span with the class that adds a red x to indicate there's an error in this fieldset (accordion tab)
      $('<span class="clientSideError"></span>').insertAfter($fieldsetErrorAnchor);
      
      //alert("i just inserted the 'clientSideError' span after anchor element: " + $fieldsetErrorAnchor.text() );
      
      if($mainFieldset.attr('id') == 'jobVersionFieldset' ) {
        
        // Extract the name of the matching tab class from 
        //   the namespaced-prefixed class of the step fieldset with an error
        //   (i.e., the tab's class might be 'misc', while the fieldset's class would be 'tab-misc')
        $stepFieldset = $this.closest('.step'); // get the step fieldset of 'this' error field
        
        var stepFieldsetClassStr = $stepFieldset.attr('class');
        //alert("The classes of the error fieldset are: \"" + stepFieldsetClassStr +"\"");
        
        var regExPatternObj = /tab-(.+)/;
        
        //alert("Regex obj is: " + regExPatternObj);
        
        var matches = regExPatternObj.exec(stepFieldsetClassStr);
        var tabClass = matches[1];
        //alert("tabClass is: \"" + tabClass + "\"");
        
        var anchorHandle = "#navigation a." + tabClass;
        var $anchorTabWithError = $mainFieldset.find(anchorHandle);
        //alert("Anchor text of error tab: \"" + $anchorTabWithError.text() + "\"");
        $('<span class="clientSideError"></span>').insertAfter($anchorTabWithError);
      }
    });

  } ////////////////// end handleServerValidationError() ////////
  
  
  
	/*
	if there are errors don't allow the user to submit
	*/
	$('#registerButton').bind('click',function(){
		if($('#slidingFormFieldsetDiv').data('errors')){
			alert('Please correct the errors in the Form');
			return false;
		}	
	});
});